// 打开数据库连接
const request: IDBOpenDBRequest = indexedDB.open("myDatabase", 1);
let db: IDBDatabase;

request.onerror = function (event) {
  console.log("数据库打开失败");
};

request.onsuccess = function (event) {
  db = event.target.result;
  // 执行事务
  doTransaction();
};

function doTransaction() {
  // 开启读写事务
  const transaction:IDBTransaction = db.transaction(["customers"], "readwrite");
  const objectStore = transaction.objectStore("customers");

  // 添加数据
  const addRequest = objectStore.add({
    id: 1,
    name: "John Doe",
    email: "john@example.com",
  });

  addRequest.onerror = function (event) {
    console.log("数据添加失败");
  };

  addRequest.onsuccess = function (event) {
    console.log("数据添加成功");
  };

  // 查询数据
  const getRequest = objectStore.get(1);

  getRequest.onerror = function (event) {
    console.log("数据查询失败");
  };

  getRequest.onsuccess = function (event) {
    const result = event.target.result;
    console.log("查询结果:", result);
  };

  // 更新数据
  const updateRequest = objectStore.put({
    id: 1,
    name: "John Smith",
    email: "john@example.com",
  });

  updateRequest.onerror = function (event) {
    console.log("数据更新失败");
  };

  updateRequest.onsuccess = function (event) {
    console.log("数据更新成功");
  };

  // 删除数据
  const deleteRequest = objectStore.delete(1);

  deleteRequest.onerror = function (event) {
    console.log("数据删除失败");
  };

  deleteRequest.onsuccess = function (event) {
    console.log("数据删除成功");
  };

  // 事务完成
  transaction.oncomplete = function (event) {
    console.log("事务完成");
    // 关闭数据库连接（这一步也可以省略）
    db.close();
  };

  transaction.onerror = function(event) {
    const error = event.target.error; // 获取错误对象
    console.log("事务错误:", error);

    console.log("错误码:", error.code);
    console.log("错误名称:", error.name);
    console.log("错误信息:", error.message);

    // 可能还有其他的错误属性可供查看

    // 如果需要进一步处理错误，可以抛出异常或执行其他操作
    // throw new Error("事务发生错误");
  };
  
}
